<template>
  <div class="vt-cart">
    <slot></slot>
  </div>
</template>

<script>
  export default {
    /*
    * 不能绑定相同引用类型值。
    * */
    name: 'cart',
    model: {
      prop: 'checkArr',
      event: 'check-group'
    },
    props: {
      checkArr: {
        type: Array,
        default(){
          return []
        }
      }
    },
    provide () {
      return {
		comName: '<Cart>',
        test: this.checkArr
      }
    },
    mounted() {
      let idx
      let hasHeader = this.$children.some((i,n)=>{
        idx = n
        return i.comName === '<CartHeader>'
      })
      if(hasHeader){
        this.$children[idx].checkAllTogger(this.checkArr.length === (this.$children.length - 1))
      }else{
        this.$children[idx].checkAllTogger(this.checkArr.length === this.$children.length)
      }
    },
    beforeMount() {
      let _this = this
      this.$on('cart-item-update', function () {
        let idx
        let hasFalse = false
        _this.$children.forEach((i,n)=>{
          if(i.comName === '<CartHeader>') {
            idx = n
          }else{
            if(i.cartItemChecker === false) {
              hasFalse = true
            }
          }
        })
        _this.$children[idx].checkAllTogger(!hasFalse)
      })
    },
    created() {
      let _this = this
      this.$on('click-checkbox-group-item', function (x) {
        let Arr = this.checkArr
        function setModelData() {
          let idx
          let ok = Arr.some((i,n)=>{
            idx = n
            return i===x
          })
          if(ok){
            Arr.splice(idx,1)
          }else{
            Arr.push(x)
          }
        }
        setModelData()
        this.$emit('check-group', Arr)
      })

      this.$on('click-toggle-all', function () {
        this.toggleAll()
      })
    },
    methods: {
      checkAll() {
        this.$children.forEach(i=>{
          if(i.comName === '<CartItem>' && !i.cartItemChecker){
            i.onCheck()
          }
        })
      },
      cleanAll() {
        this.$children.forEach(i=>{
          if(i.comName === '<CartItem>' && i.cartItemChecker){
            i.onCheck()
          }
        })
      },
      toggleAll(){
        let cartItemArr = []
        this.$children.forEach(i=>{
          if(i.comName === '<CartItem>'){
            cartItemArr.push(i.comName)
          }
        })
        if(this.checkArr.length === cartItemArr.length){
          this.cleanAll()
        }else{
          this.checkAll()
        }
      }
    }
  }
</script>

<style scoped>

</style>
